package rai;

import java.io.IOException;

import rai.service.rep.ListeRepertoires;
import rai.service.rep.Repertoire;
import rai.service.transport.Client;

public class RaiClientListeRepertoires implements ListeRepertoires {
	Client leClient;

	public RaiClientListeRepertoires(String hostname) throws IOException {
		this(hostname, 8787);
	}

	public RaiClientListeRepertoires(String hostname, int port)
			throws IOException {
		this.leClient = new Client(hostname, port);
	}

	public void authentification(String login, String password)
			throws UtilisateurInconnueException {
		try {
			this.leClient.writeString(login);
			this.leClient.writeString(password);

			if (!this.leClient.readBoolean())
				throw new UtilisateurInconnueException(login);
		} catch (IOException e) {
			new RuntimeException("Erreur E/S");
			e.printStackTrace();
		}
	}

	public boolean creerRepertoire(String identifiant) {
		try {
			this.leClient.writeObject(Commande.NewRepertoire);
			this.leClient.writeString(identifiant);
			return this.leClient.readBoolean();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public String[] listerRepertoires() {
		try {
			this.leClient.writeObject(Commande.ListeRepertoires);
			this.leClient.readInt();
			int nbNom = this.leClient.readInt();
			System.out.println("NbNom: " + nbNom);
			String[] sortie = new String[nbNom];
			for (int i = 0; i < nbNom; i++)
				sortie[i] = this.leClient.readString();
			return sortie;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public Repertoire rechercherRepertoire(String identifiant) {
		try {
			this.leClient.writeObject(Commande.FindRepertoire);
			this.leClient.writeString(identifiant);
			return (this.leClient.readBoolean()) ? new RaiClientRepertoire(
					leClient) : null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public boolean supprimerRepertoire(String identifiant) {
		try {
			this.leClient.writeObject(Commande.RemRepertoire);
			this.leClient.writeString(identifiant);
			return this.leClient.readBoolean();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public Boolean sauverListeRepertoires() {
		try {
			this.leClient.writeObject(Commande.SaveListeRepertoires);
			return this.leClient.readBoolean();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public void quitterListeRepertoires() {
		try {
			this.leClient.writeObject(Commande.QuitListeRepertoires);
		} catch (IOException e) {
					}
	}
}
